
package com.yimixian.app.fragment;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Entries;
import com.yimixian.app.model.Entry;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.User;
import com.yimixian.app.model.UserLevel;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.ClearRedPointAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.CircleImageView;
import com.yimixian.app.ui.pulltozoomview.PullToZoomScrollViewEx;
import com.yimixian.app.user.SettingItemView;
import com.yimixian.app.user.SettingsActivity;
import com.yimixian.app.user.UserInfoEditActivity;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;

public class MyFragment extends BaseHttpFragment implements View.OnClickListener {

    public static final int NORMAL = -1;// 编辑个人资料页面
    public static final int EDITPERSON = 6;// 编辑个人资料页面
    public static final int BALANCE = 1;// 用户余额
    public static final int COUPON = 2;// 优惠券
    public static final int POINT = 3;// 积分
    public static final int INVITE = 4;// 邀请好友
    public static final int ADDRESS = 5;// 地址

    private static final int SETTINGS_REQUEST = 0;
    private static final int SPACE_NUMBER = 4;
    PullToZoomScrollViewEx scrollView;
    CircleImageView mIvAvator;
    TextView mTvName;
    TextView mTvTel;
    // TextView mTvLevel;
    // TextView mTvPoint;
    TextView mTvAccountBalance;
    TextView mTvMyCoupon;
    TextView mTvMyPoint;
    SettingItemView mItemInvite;
    SettingItemView mItemEnterpriseBuyingGroup;
    SettingItemView mItemTuan;
    SettingItemView mItemManageAddress;
    SettingItemView mItemContactService;
    SettingItemView mItemSetting;
    RelativeLayout mRlAccount;
    RelativeLayout mRlCoupon;
    RelativeLayout mRlPoint;
    TextView toLogin;
    RelativeLayout userIsLogin;

    // 2.0.1优化新加
    RelativeLayout mHeadTopView;
    ImageView mLevelView;
    ImageView mCurrentLevelImg;
    ImageView mNextLevelImg;
    ProgressBar mProgressBar;
    TextView mIntergrateView;
    TextView mIntergrateLeftView;
    TextView mboundPoint;
    RelativeLayout mIntergrateContainerView;
    TextView mClickEditView;
    SettingItemView mCustomerService;
    RelativeLayout mIntergrateContainer;
    TextView mLevelText;
    View sortline_view_first, line_view_first, line_view_two;

    protected BaseNaviFragmentGroupActivity mActivity;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    private User mCurrentUser;
    private AppConfig mAppConfig;
    private ClearRedPointAPI mClearRedPointAPI;

    private LinearLayout ll_config; //动态配置布局
    private float dentity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        View view = inflater.inflate(R.layout.fragment_my, null);
        if (getActivity() != null) {
            mActivity = (BaseNaviFragmentGroupActivity) getActivity();
        }
        scrollView = (PullToZoomScrollViewEx) view.findViewById(R.id.scroll_view);
        dentity = getActivity().getResources().getDisplayMetrics().density;
        loadViewForCode();
        initView();
        return view;
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (StringUtils.isEmpty(DataManager.getInstance()
                .<String>get(CacheKeys.TOKEN)))
            return;
        // 清除小红点
        if (requestKeys != null && requestKeys.equals(ClearRedPointAPI.CLEARURL)) {
            mClearRedPointAPI = new ClearRedPointAPI(mDataManager
                        .<String>get(CacheKeys.TOKEN), Constants.RedPointType.BOUNS, this);
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        // 清除小红点
        if (url.contains(ClearRedPointAPI.CLEARURL)) {
            mboundPoint.setVisibility(View.GONE);
            EventBus.getDefault().post(new OrderListPointTab(0, Constants.RedPointType.BOUNS, false));
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {

    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (key != null && mClearRedPointAPI != null && key.equals(ClearRedPointAPI.CLEARURL)) {
            mClearRedPointAPI.toClearRedPoint();
        }
    }

    private void loadViewForCode() {

        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.profile_new_head_view,
                null, false);
        View zoomView = LayoutInflater.from(getActivity()).inflate(R.layout.profile_zoom_view,
                null, false);
        View contentView = LayoutInflater.from(getActivity()).inflate(
                R.layout.profile_content_view, null, false);
        mIvAvator = (CircleImageView) headView.findViewById(R.id.iv_avator);
        mTvName = (TextView) headView.findViewById(R.id.tv_name);
        mTvTel = (TextView) headView.findViewById(R.id.tv_tel);
        mHeadTopView = (RelativeLayout) headView.findViewById(R.id.head_view);
        mLevelView = (ImageView) headView.findViewById(R.id.imageview_level);
        mProgressBar = (ProgressBar) contentView.findViewById(R.id.intergrate_progressbar);
        mIntergrateView = (TextView) contentView.findViewById(R.id.intergrate);
        mIntergrateLeftView = (TextView) contentView.findViewById(R.id.intergrate_left);
        mIntergrateContainerView = (RelativeLayout) contentView.findViewById(R.id.intergrate_view);
        mClickEditView = (TextView) headView.findViewById(R.id.text_edit);
        mLevelText = (TextView) headView.findViewById(R.id.tv_level_text);
        // mTvLevel = (TextView) headView.findViewById(R.id.tv_level);
        // mTvPoint = (TextView) headView.findViewById(R.id.tv_point);

        mTvAccountBalance = (TextView) contentView.findViewById(R.id.tv_account_balance);
        mTvMyCoupon = (TextView) contentView.findViewById(R.id.tv_my_coupon);
        mTvMyPoint = (TextView) contentView.findViewById(R.id.tv_my_point);
        mboundPoint = (TextView) contentView.findViewById(R.id.bound_point);
        mItemInvite = (SettingItemView) contentView.findViewById(R.id.item_invite);
        mItemEnterpriseBuyingGroup = (SettingItemView) contentView.findViewById(R.id.item_enterprise_buying_group);
        mItemTuan = (SettingItemView) contentView.findViewById(R.id.item_tuan);
        mItemManageAddress = (SettingItemView) contentView.findViewById(R.id.item_manage_address);
        mItemContactService = (SettingItemView) contentView.findViewById(R.id.item_contact_service);
        mItemSetting = (SettingItemView) contentView.findViewById(R.id.item_setting);
        mCustomerService = (SettingItemView) contentView.findViewById(R.id.customer_service);
        mRlAccount = (RelativeLayout) contentView.findViewById(R.id.rl_account);
        mRlCoupon = (RelativeLayout) contentView.findViewById(R.id.rl_coupon);
        mRlPoint = (RelativeLayout) contentView.findViewById(R.id.rl_point);
        toLogin = (TextView) headView.findViewById(R.id.to_login);
        sortline_view_first = contentView.findViewById(R.id.sortline_view_first);
        line_view_first = contentView.findViewById(R.id.line_view_first);
        line_view_two = contentView.findViewById(R.id.line_view_two);
        userIsLogin = (RelativeLayout) headView.findViewById(R.id.user_islogin);
        mNextLevelImg = (ImageView) contentView.findViewById(R.id.img_next_level);
        mCurrentLevelImg = (ImageView) contentView.findViewById(R.id.img_current_level);
        mIntergrateContainer = (RelativeLayout) contentView
                .findViewById(R.id.intergrate_containner);
        ll_config = (LinearLayout) contentView.findViewById(R.id.ll_config);

        scrollView.setHeaderView(headView);
        scrollView.setZoomView(zoomView);
        scrollView.setScrollContentView(contentView);
    }

    public void initView() {
        if (isAdded()) {
            mItemInvite
                    .bind(R.drawable.ic_setting_invite, getString(R.string.invite_friend), false);
            mItemInvite.setTextColor(ContextCompat.getColor(getActivity(), R.color.home_orange_color));
            mItemEnterpriseBuyingGroup.bind(R.drawable.ic_enterprise_buying_group, "企业团购", false);
            mItemTuan.bind(R.drawable.im_mine_tuan, getString(R.string.mine_tuan), false);
            mItemManageAddress.bind(R.drawable.ic_setting_manage_address,
                    getString(R.string.manage_address), false);
            mItemContactService.bind(R.drawable.ic_setting_custom_service,
                    getString(R.string.contact_custom_service), true);
            mItemSetting.bind(R.drawable.ic_setting_setting, getString(R.string.setting), false);
            mCustomerService.bind(R.drawable.ic_customer_service,
                    getString(R.string.customer_service), false);
            mItemInvite.setOnClickListener(this);
            mItemEnterpriseBuyingGroup.setOnClickListener(this);
            mItemTuan.setOnClickListener(this);
            mItemManageAddress.setOnClickListener(this);
            mItemContactService.setOnClickListener(this);
            mCustomerService.setOnClickListener(this);
            mItemSetting.setOnClickListener(this);
            mRlAccount.setOnClickListener(this);
            mRlCoupon.setOnClickListener(this);
            mRlPoint.setOnClickListener(this);
            mHeadTopView.setOnClickListener(this);
            toLogin.setOnClickListener(this);
            mIntergrateContainerView.setOnClickListener(this);
        }
        toLogin.setVisibility(isLogin() ? View.GONE : View.VISIBLE);
        userIsLogin.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        mIntergrateContainerView.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        mClickEditView.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
    }

    public void showBonusRedPoint(boolean isShow){
        if (mboundPoint != null) mboundPoint.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
        fetchData(false);
        onDataFetched();
        if (isAdded()){
            View view = ((YMXMainActivity)getActivity()).boundPoint;
            if (view != null && view.getVisibility() == View.VISIBLE){
                mboundPoint.setVisibility(View.VISIBLE);
            }else {
                mboundPoint.setVisibility(View.GONE);
            }

            mAppConfig = SharedPreferencesHelper.getAppConfig();
            if(mAppConfig != null){
                updateItem(mAppConfig);
            }
        }
    }

    private void fetchData(boolean isUseCurrentUserCache) {
        mYmxDataService
                .getAppConfig(true)
                .zipWith(mYmxDataService.getCurrentUser(isUseCurrentUserCache),
                        new Func2<AppConfig, User, Boolean>() {
                            @Override
                            public Boolean call(AppConfig appConfig, User user) {

                                if (user == null) {
                                    // UiUtils.showToast(getActivity(),
                                    // getString(R.string.user_unlogin));
                                    return false;
                                }

                                mDataManager.put(CacheKeys.CURRENT_USER, user);
                                return true;
                            }
                        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                if (aBoolean) {
                                    onDataFetched();
                                }
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                UiUtils.toastError(
                                        SystemFramework.getInstance().getGlobalContext(), throwable);
                            }
                        }
                );
    }


    private void onDataFetched() {
        hideView();
        if (toLogin == null)
            return;
        toLogin.setVisibility(isLogin() ? View.INVISIBLE : View.VISIBLE);
        userIsLogin.setVisibility(isLogin() ? View.VISIBLE : View.INVISIBLE);
        mIntergrateContainerView.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        mClickEditView.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        if (!isLogin()) {
            mIntergrateContainerView.setVisibility(View.GONE);
            mIvAvator.setImageResource(R.drawable.ic_my_head_pic);
            mTvAccountBalance.setText("0");
            mTvMyCoupon.setText("0");
            mTvMyPoint.setText("0");
            mIntergrateLeftView.setText("");
            mIntergrateView.setText("0");
            mClickEditView.setVisibility(View.GONE);
            return;
        }
        mCurrentUser = mDataManager.get(CacheKeys.CURRENT_USER);
        if (mCurrentUser != null) {
            UserLevel mLevel = mCurrentUser.level;
            if (mLevel != null) {
                // String level =
                // String.format(getString(R.string.user_info_level),
                // mLevel.level);
                // mTvLevel.setText(level);
                // String jifen =
                // String.format(getString(R.string.user_info_jifen),
                // String.valueOf(mLevel.accumulativeCredit),
                // String.valueOf(mLevel.shortfallCredit));
                // mTvPoint.setText(jifen);
                if (isAdded()) {
                    float sizePromotion = getResources().getDimension(R.dimen.level_img);
                    Picasso.with(getActivity())
                            .load(DataManager.getInstance().getImageUrl(mLevel.levelImg,
                                    (int) sizePromotion))
                            .into(mLevelView);
                    Picasso.with(getActivity())
                            .load(DataManager.getInstance().getImageUrl(mLevel.progressStartImg,
                                    (int) sizePromotion))
                            .into(mCurrentLevelImg);
                    Picasso.with(getActivity())
                            .load(DataManager.getInstance().getImageUrl(mLevel.progressEndImg,
                                    (int) sizePromotion))
                            .into(mNextLevelImg);
                }
                mLevelText.setText(mLevel.levelText);
                mIntergrateView.setText(String.valueOf(mLevel.accumulativeCredit));
                mIntergrateLeftView.setText(mLevel.progressText);
                mProgressBar.setMax(100);
                mProgressBar.setProgress(100);
                setProgressBarGuide(mLevel);
            }
            // if (mCurrentUser.sex == 0) {// 默认
            if(Strings.isNullOrEmpty(mCurrentUser.head_img))
                mIvAvator.setImageResource(R.drawable.ic_my_head_pic);
            else
                Picasso.with(getActivity()).load(mCurrentUser.head_img).placeholder(R.drawable.ic_my_head_pic).into(mIvAvator);
            // } else if (mCurrentUser.sex == 1) {// 男
            // mIvAvator.setImageResource(R.drawable.ic_my_head_pic);
            // } else {// 女
            // mIvAvator.setImageResource(R.drawable.ic_my_head_pic);
            // }
            mTvName.setText(StringUtils.isEmpty(mCurrentUser.nickName) ? "" : mCurrentUser.nickName);
            mTvTel.setText(StringUtils.isEmpty(mCurrentUser.tel) ? "" : ("" + mCurrentUser.tel));
            mTvAccountBalance.setText(Strings.getDecimalWith2Number(Double
                    .valueOf(mCurrentUser.remainingBalance)));
            int couponCount = mCurrentUser.avaliableBonusCount;
            mTvMyCoupon.setText(String.valueOf(couponCount));
            mTvMyPoint.setText(String.valueOf(mCurrentUser.remainingCredit));
        }

    }

    /**
     * 设置进度条上的标识符号
     * 
     * @param mLevel
     */
    private void setProgressBarGuide(final UserLevel mLevel) {
        if(getContext() == null) {
            return ;
        }
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        double currentWidth = ((double)(mLevel.progress) / 100) * (width-60);
        final RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)mProgressBar.getLayoutParams();

//        if(currentWidth < 0.05) {
//            //处理0这种情况
//            layoutParams.width = 0;
//            mProgressBar.setLayoutParams(layoutParams);
//        } else if(((double)(mLevel.progress) / 100) < 0.03) {
//            layoutParams.width = (int)(0.03 * width);
//            mProgressBar.setLayoutParams(layoutParams);
//        } else {
            ValueAnimator valueAnimator = new ValueAnimator();
            valueAnimator.setDuration(1000);
            valueAnimator.setTarget(mProgressBar);
            valueAnimator.setInterpolator(new AccelerateInterpolator());
            valueAnimator.setFloatValues(0, (float) currentWidth);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float width = (float) animation.getAnimatedValue();
//                    if (width < 0.05) {
//                        //处理0这种情况
//                        layoutParams.width = 0;
//                    } else if (((double) (mLevel.progress) / 100) < 0.03) {
//                        layoutParams.width = (int) (0.03 * width);
//                    } else {
                        layoutParams.width = (int) width;
//                    }
                    mProgressBar.setLayoutParams(layoutParams);
                }
            });
            valueAnimator.start();
//        }

        // 设置文字的位置
        mIntergrateContainer.measure(0, 0);
        int containerWidth = mIntergrateContainer.getMeasuredWidth();
        if (currentWidth > containerWidth) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIntergrateContainer
                    .getLayoutParams();
            params.leftMargin = (int) currentWidth - containerWidth;
            mIntergrateContainer.setLayoutParams(params);
        } else {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIntergrateContainer
                    .getLayoutParams();
            params.leftMargin = 30;
            mIntergrateContainer.setLayoutParams(params);
        }
        if (currentWidth + containerWidth + 60 > width) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mIntergrateContainer
                    .getLayoutParams();
            params.leftMargin = width - 100 - containerWidth;
            mIntergrateContainer.setLayoutParams(params);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_invite:// 邀请好友大礼包
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, INVITE);
                    return;
                }
                if (mAppConfig == null)
                    return;
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_INVITE_FRIENDS_CLICK);
                Intent intentInvite = new Intent(getActivity(), WebViewActivity.class);
                intentInvite.putExtra(WebViewActivity.EXTRA_TITLE,
                        getString(R.string.invite_friend));
                intentInvite.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.invitationUrl);
                startActivity(intentInvite);
                break;
            case R.id.item_enterprise_buying_group:// 企业团购
                if (mAppConfig == null)
                    return;
                Intent intentBuyGroup = new Intent(getActivity(), WebViewActivity.class);
                intentBuyGroup.putExtra(WebViewActivity.EXTRA_TITLE,
                    "企业团购");
                intentBuyGroup.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.enterpriseBuyingGroup);
                startActivity(intentBuyGroup);
                break;
            case R.id.item_tuan:// 团订单
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, INVITE);
                    return;
                }
                if (mAppConfig == null)
                    return;
                Intent intentTuan = new Intent(getActivity(), WebViewActivity.class);
                intentTuan.putExtra(WebViewActivity.EXTRA_TITLE, getString(R.string.mine_tuan));
                intentTuan.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.buyingGroupPlacesUrl);
                startActivity(intentTuan);
                break;
            case R.id.rl_account:// 账户余额
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, BALANCE);
                    return;
                }
                if (mAppConfig == null)
                    return;
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_ACCOUNT_BAlANCE_CLICK);
                Intent intentAccount = new Intent(getActivity(), WebViewActivity.class);
                intentAccount.putExtra(WebViewActivity.EXTRA_TITLE, "账户余额");
                intentAccount.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.rechargeUrl);
                startActivity(intentAccount);
                break;
            case R.id.rl_coupon:// 我的水果券
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, COUPON);
                    return;
                }
                if (mAppConfig == null)
                    return;
                if (isAdded()){
                    View view = ((YMXMainActivity)getActivity()).boundPoint;
                    if (view != null && view.getVisibility() == View.VISIBLE)
                        fetchData(true, mClearRedPointAPI.CLEARURL);
                }
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_FRUIT_COUPON_CLICK);
                Intent intentCoupon = new Intent(getActivity(), WebViewActivity.class);
                intentCoupon.putExtra(WebViewActivity.EXTRA_TITLE,
                        getString(R.string.personal_mine_bonus));
                intentCoupon.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.bonusUrl);
                startActivity(intentCoupon);
                break;
            case R.id.rl_point:// 我的积分
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, POINT);
                    return;
                }
                if (mAppConfig == null)
                    return;
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_VANTAGES_CLICK);
                Intent intentMall = new Intent(getActivity(), WebViewActivity.class);
                intentMall.putExtra(WebViewActivity.EXTRA_TITLE, "我的积分");
                intentMall.putExtra(WebViewActivity.EXTRA_URL, mAppConfig.creditMallUrl);
                startActivity(intentMall);
                break;
            case R.id.item_contact_service:// 联系客服
                String tel;
                if (mAppConfig == null || StringUtils.isEmpty(mAppConfig.customerServiceTel)) {
                    tel = SharedPreferencesHelper.getString(Constants.CONNECT_SERVICE);
                } else {
                    tel = mAppConfig.customerServiceTel;
                }
                if (tel == null)
                    return;
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_CUSTOM_SERVICE_TEL_CLICK);
                Intent intentContact = new Intent(Intent.ACTION_CALL);
                intentContact.setAction(Intent.ACTION_DIAL);
                intentContact.setData(Uri.parse("tel:" + tel));
                startActivity(intentContact);
                break;
            case R.id.item_manage_address:// 地址管理
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, ADDRESS);
                    return;
                }
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_ADDRESS_MANAGER_CLICK);
                Intent intent = new Intent(getActivity(), ShowAddressesActivity.class).putExtra(
                        ShowAddressesActivity.EXTRA_MODE,
                        ShowAddressesActivity.MANAGE_ADDRESS_MODE);
                startActivity(intent);
                break;
            case R.id.item_setting:// 设置
                MobclickAgent.onEvent(getActivity(), StatConstants.MY_SETTING_CLICK);
                Intent intentSetting = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intentSetting);
                break;
            case R.id.head_view:
                if (!isLogin()) {
                    UserRegistrationActivity.animtionToLogin(mActivity, EDITPERSON);
                    return;
                }
                UserInfoEditActivity.startActivity(getActivity());
                break;
            case R.id.to_login:// 登录按钮
                UserRegistrationActivity.animtionToLogin(mActivity, NORMAL);
                break;
            case R.id.customer_service: // 客户服务按钮
                AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
                if (appConfig == null || StringUtils.isEmpty(appConfig.serviceTermsUrl))
                    return;
                Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                intent1.putExtra(WebViewActivity.EXTRA_TITLE,
                        getResources().getString(R.string.setting_service));
                intent1.putExtra(WebViewActivity.EXTRA_URL, appConfig.serviceTermsUrl);
                startActivity(intent1);
                break;
            case R.id.intergrate_view:// 会员规则模块
                AppConfig appConfig1 = mDataManager.get(CacheKeys.APP_CONFIG);
                if (appConfig1 == null || StringUtils.isEmpty(appConfig1.memberIntroUrl))
                    return;
                Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
                intent2.putExtra(WebViewActivity.EXTRA_TITLE,
                        getResources().getString(R.string.member_rule));
                intent2.putExtra(WebViewActivity.EXTRA_URL, appConfig1.memberIntroUrl);
                startActivity(intent2);
                break;
        }
    }

    /**
     * 根据config返回 显示隐藏view
     */
    public void hideView(){
        AppConfig appConfig = DataManager.getInstance().get(CacheKeys.APP_CONFIG);
        if (appConfig != null){
            if (StringUtils.isEmpty(appConfig.invitationUrl)){
                sortline_view_first.setVisibility(View.GONE);
                line_view_first.setVisibility(View.GONE);
                // 邀请好友大礼包
                mItemInvite.setVisibility(View.GONE);
                // 团订单
                mItemTuan.setVisibility(View.GONE);
            }else {
                
                    line_view_first.setVisibility(View.GONE);
               
                sortline_view_first.setVisibility(View.VISIBLE);
                // 邀请好友大礼包
                mItemInvite.setVisibility(StringUtils.isEmpty(appConfig.invitationUrl) ?
                        View.GONE : View.VISIBLE);
                // 团订单
                mItemTuan.setVisibility(View.GONE);
            }
            mItemEnterpriseBuyingGroup.setVisibility(StringUtils.isEmpty(appConfig.enterpriseBuyingGroup)?View.GONE : View.VISIBLE);
//            mItemContactService.setVisibility(StringUtils.isEmpty(appConfig.invitationUrl) ?
//                    View.GONE : View.VISIBLE);
            // 客户服务按钮
            mCustomerService.setVisibility(StringUtils.isEmpty(appConfig.serviceTermsUrl) ?
                    View.GONE : View.VISIBLE);
            line_view_two.setVisibility(StringUtils.isEmpty(appConfig.serviceTermsUrl) ?
                    View.GONE : View.VISIBLE);
        }

    }

    /** 判断是否登录 */
    public boolean isLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            return false;
        }
        return true;
    }

    /**
     * 根据配置接口动态加载项
     * @param appConfig
     */
    public void updateItem(final AppConfig appConfig){

        ll_config.removeAllViews();
        List<Entries> entries = appConfig.userCenterEntries;
        for (Entries each : entries) {
            for (int i = 0; i < each.entries.size(); i++) {
                final Entry each_sub = each.entries.get(i);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                SettingItemView item = new SettingItemView(getActivity());
                if(i == 0)
                    item.setPadding(0, (int) (5 * dentity), 0, 0);
                item.bind(each_sub);
                if(!StringUtils.isEmpty(each_sub.url)){
                    if(each_sub.url.startsWith("http")){
                        item.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                intent.putExtra(WebViewActivity.EXTRA_TITLE, each_sub.title);
                                intent.putExtra(WebViewActivity.EXTRA_URL, each_sub.url);
                                startActivity(intent);
                            }
                        });
                    }else if(each_sub.url.indexOf("settings_page") > 0){
                        item.setId(R.id.item_setting);
                        item.setOnClickListener(MyFragment.this);
                    }else if(each_sub.url.indexOf("phone_number") > 0){
                        item.setId(R.id.item_contact_service);
                        item.setOnClickListener(MyFragment.this);
                    }else if(each_sub.url.indexOf("manage_addresses_page") > 0){
                        item.setId(R.id.item_manage_address);
                        item.setOnClickListener(MyFragment.this);
                    }

                }
                ll_config.addView(item);
                LinearLayout ll_line = new LinearLayout(getActivity());
                ll_line.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (1 * dentity)));
                ll_line.setBackgroundColor(Color.WHITE);
                ll_line.setPadding((int) (10 * dentity), 0, 0, 0);
                if(i != each.entries.size() - 1){
                    View v_line = new View(getActivity());
                    v_line.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (1 * dentity)));
                    v_line.setBackgroundColor(getResources().getColor(R.color.my_devider_color));
                    ll_line.addView(v_line);
                }
                ll_config.addView(ll_line);

            }
        }

    }
}
